import React, { createContext, useState } from 'react';
import { MenuItemProps } from './menuItem';
import classNames from 'classnames';
// 字符串字面量限制类型取值
type MenuMode = 'horizontal' | 'vertical';
type selectCallback = (selectedIndex: number) => void;
export interface MenuProps {
  defaultIndex?: number;
  className?: string;
  mode?: MenuMode;
  style?: React.CSSProperties;
  // 回调
  onSelected?: selectCallback;
}
// 属性透传
interface IMenuContext {
  index: number;
  onSelected?: selectCallback;
}
const Menu: React.FC<MenuProps> = (props) => {
  // eslint-disable-next-line
  const {className, mode, style, children, defaultIndex, onSelected} = props;
  const [currentActive, setActive] = useState(defaultIndex)
  const classes = classNames('xd-menu', className, {
    'menu-vertical': mode === 'vertical',
    'menu-horizontal': mode === 'horizontal'
  });
  const handleClick = (index: number) => {
    setActive(index)
    if (onSelected) {
      onSelected(index)
    }
  }
  const renderChildren = () => {
    return React.Children.map(children, (child, index) => {
      const childElement = child as React.FunctionComponentElement<MenuItemProps>;
      const {displayName} = childElement.type;
      if (displayName === 'MenuItem') {
        return React.cloneElement(childElement, {
          index
        });
      } else {
        console.error('error: menu has a child is not a menuItem component');
      }
    })
  }
  // 将回调和当前索引传递到子组件
  const passedContext: IMenuContext = {
    index: currentActive? currentActive:0,
    onSelected: handleClick
  }
  return (
    // data-testid="test-menu"用于测试的id
    <ul className={classes} style={style} data-testid="test-menu">
      <MenuContext.Provider value={passedContext}>
        {renderChildren()}
      </MenuContext.Provider>
    </ul>
  );
};

export const MenuContext = createContext<IMenuContext>({index: 0})

Menu.defaultProps = {
  defaultIndex: 0,
  mode: 'horizontal',
};

export default Menu;